package com.ruoyi.merchant.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.merchant.domain.Combo;
import com.ruoyi.merchant.domain.dto.ComboSubmitDTO;
import com.ruoyi.merchant.service.IComboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 套餐管理Controller
 */
@RestController
@RequestMapping("/merchant/combo")
public class ComboController extends BaseController {

    @Autowired
    private IComboService comboService;

    /**
     * 查询套餐列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Combo combo) {
        startPage();
        List<Combo> list = comboService.selectComboList(combo);
        return getDataTable(list);
    }

    /**
     * 按状态统计套餐数量
     */
    @GetMapping("/count-by-status")
    public AjaxResult countByStatus() {
        Map<String, Object> countData = comboService.countComboByStatus();
        return success(countData);
    }

    /**
     * 获取套餐详细信息（包含商品列表）
     */
    @GetMapping(value = "/{comboId}")
    public AjaxResult getInfo(@PathVariable("comboId") Long comboId) {
        Combo combo = comboService.selectComboByComboId(comboId);
        return success(combo);
    }

    /**
     * 新增套餐
     */
    @Log(title = "套餐管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ComboSubmitDTO comboSubmitDTO) {
        int result = comboService.insertCombo(comboSubmitDTO);
        if (result > 0) {
            return success("套餐创建成功");
        }
        return error("新增套餐失败");
    }

    /**
     * 修改套餐
     */
    @Log(title = "套餐管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ComboSubmitDTO comboSubmitDTO) {
        return toAjax(comboService.updateCombo(comboSubmitDTO));
    }

    /**
     * 删除套餐
     */
    @Log(title = "套餐管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{comboIds}")
    public AjaxResult remove(@PathVariable Long[] comboIds) {
        return toAjax(comboService.deleteComboByComboIds(comboIds));
    }

    /**
     * 批量修改套餐状态（上下架）
     */
    @Log(title = "套餐上下架", businessType = BusinessType.UPDATE)
    @PutMapping("/status")
    public AjaxResult updateStatus(@RequestBody Map<String, Object> params) {
        Long[] comboIds = ((List<Integer>) params.get("comboIds"))
                .stream()
                .map(Long::valueOf)
                .toArray(Long[]::new);
        Integer status = (Integer) params.get("status");
        return toAjax(comboService.updateComboStatus(comboIds, status));
    }
}
